﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Jemgine.EffectEditor
{
    public partial class MainWindow : Form
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        EditorState _editorState;

        public void SetEditorState(EditorState ES)
        {
            _editorState = ES;
            renderEffect.SetEditorState(ES);
            ES.EffectLoaded += BuildTreeView;
            ES.UpdateStatus += UpdateStatus;
            ES.GetZoomFactor = () =>
                {
                    try
                    {
                        return Convert.ToSingle(this.zoomBox.Text);
                    }
                    catch (Exception) { return 1.0f; }
                };
        }

        private SaveChanges.Action PromptSaveChanges()
        {
            if (_editorState._hasUnsavedChanges)
            {
                var SaveDialog = new SaveChanges();
                SaveDialog.ShowDialog();
                var Result = SaveDialog.DialogResult;
                if (Result == SaveChanges.Action.Cancel)
                    return SaveChanges.Action.Cancel;
                if (Result == SaveChanges.Action.Save)
                {
                    if (_editorState.FileSet)
                        _editorState.SaveMap();
                    else
                    {
                        var sfd = new System.Windows.Forms.SaveFileDialog();
                        sfd.Filter = "Particle Effects (*.pfx)|*.pfx|All Files|*.*";

                        if (sfd.ShowDialog(this) == DialogResult.OK)
                            _editorState.SaveMapAs(sfd.FileName);
                        else
                            return SaveChanges.Action.Cancel;
                    }
                }
            }
            return SaveChanges.Action.Discard;
        }

        private void UpdateStatus()
        {
            _activeParticles.Text = "Active : " + _editorState.Effect.TotalActiveParticles.ToString();
            _potentialParticles.Text = "Potential : " + _editorState.Effect.TotalPotentialParticles.ToString();
            statusStrip1.Invalidate();
            this.Invalidate();
        }

        private void BuildTreeView()
        {
            treeView.Nodes.Clear();

            foreach (var Emitter in _editorState.Effect.Emitters)
            {
                var EmitterNode = new TreeNode("Emitter");
                EmitterNode.Tag = Emitter;

                var DistributionNode = new TreeNode(
                    Emitter.Distributor == null ? "null" : Emitter.Distributor.GetType().Name);
                DistributionNode.Tag = Emitter.Distributor;

                EmitterNode.Nodes.Add(DistributionNode);

                foreach (var Modifier in Emitter.Modifiers)
                {
                    var ModifierNode = new TreeNode(Modifier.GetType().Name);
                    ModifierNode.Tag = Modifier;
                    EmitterNode.Nodes.Add(ModifierNode);
                }

                treeView.Nodes.Add(EmitterNode);
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PromptSaveChanges() == SaveChanges.Action.Cancel) return;
            _editorState.NewMap();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PromptSaveChanges() == SaveChanges.Action.Cancel) return;
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "Particle Effects (*.pfx)|*.pfx|All Files|*.*";

            if (ofd.ShowDialog(this) == DialogResult.OK)
                _editorState.OpenMap(ofd.FileName);
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_editorState.FileSet)
                _editorState.SaveMap();
            else
                saveAsToolStripMenuItem_Click(sender, e);
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
            sfd.Filter = "Particle Effects (*.pfx)|*.pfx|All Files|*.*";

            if (sfd.ShowDialog(this) == DialogResult.OK)
                _editorState.SaveMapAs(sfd.FileName);
        }

        private void addEmitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _editorState.Effect.Emitters.Add(new Particles.Emitter());
            _editorState.InitializeEffect();
            BuildTreeView();
            _editorState._hasUnsavedChanges = true;
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            propertyGrid.SelectedObject = e.Node.Tag;
        }

        private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            _editorState.InitializeEffect();
            _editorState._hasUnsavedChanges = true;
        }

        private void changeDistributionTypeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var Tag = treeView.SelectedNode == null ? null : treeView.SelectedNode.Tag;
            if (Tag is Jemgine.Particles.Emitter)
            {
                var TypeSelector = new TypeSelector(_editorState._config,
                    (A) => { return A.IsSubclassOf(typeof(Jemgine.Particles.Distributor)); });
                if (TypeSelector.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    (Tag as Jemgine.Particles.Emitter).Distributor =
                        Activator.CreateInstance(TypeSelector.ChoosenType) as Jemgine.Particles.Distributor;
                BuildTreeView();
            }
            else
                MessageBox.Show("Select an Emitter in the tree view.");
            _editorState._hasUnsavedChanges = true;                
        }

        private void addModifierToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var Tag = treeView.SelectedNode == null ? null : treeView.SelectedNode.Tag;
            if (Tag is Jemgine.Particles.Emitter)
            {
                var TypeSelector = new TypeSelector(_editorState._config,
                    (A) => { return A.IsSubclassOf(typeof(Jemgine.Particles.Modifier)); });
                if (TypeSelector.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    (Tag as Jemgine.Particles.Emitter).Modifiers.Add(
                        Activator.CreateInstance(TypeSelector.ChoosenType) as Jemgine.Particles.Modifier);
                BuildTreeView();
            }
            else
                MessageBox.Show("Select an Emitter in the tree view.");
            _editorState._hasUnsavedChanges = true;                
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var Tag = treeView.SelectedNode == null ? null : treeView.SelectedNode.Tag;
            if (Tag == null) return;

            if (Tag is Jemgine.Particles.Emitter)
                _editorState.Effect.Emitters.Remove(Tag as Jemgine.Particles.Emitter);
            if (Tag is Jemgine.Particles.Modifier)
            {
                foreach (var Emitter in _editorState.Effect.Emitters)
                    if (Emitter.Modifiers.Contains(Tag as Jemgine.Particles.Modifier))
                        Emitter.Modifiers.Remove(Tag as Jemgine.Particles.Modifier);
            }
            if (Tag is Jemgine.Particles.Distributor)
            {
                foreach (var Emitter in _editorState.Effect.Emitters)
                    if (Emitter.Distributor == Tag)
                        Emitter.Distributor = null;
            }

            BuildTreeView();
            _editorState._hasUnsavedChanges = true;
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (PromptSaveChanges() == SaveChanges.Action.Cancel)
            {
                e.Cancel = true;
                return;
            }
        }

        private void moveUpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var Tag = treeView.SelectedNode == null ? null : treeView.SelectedNode.Tag;
            if (Tag == null) return;

            if (Tag is Jemgine.Particles.Emitter)
            {
                int index = _editorState.Effect.Emitters.IndexOf(Tag as Jemgine.Particles.Emitter);
                if (index > 0)
                {
                    var Temp = _editorState.Effect.Emitters[index - 1];
                    _editorState.Effect.Emitters[index - 1] = Tag as Jemgine.Particles.Emitter;
                    _editorState.Effect.Emitters[index] = Temp;
                }
            }
            if (Tag is Jemgine.Particles.Modifier)
            {
            //    foreach (var Emitter in _editorState.Effect.Emitters)
            //        if (Emitter.Modifiers.Contains(Tag as Jemgine.Particles.Modifier))
            //            Emitter.Modifiers.Remove(Tag as Jemgine.Particles.Modifier);
            //
            }
            if (Tag is Jemgine.Particles.Distributor)
            {
                //foreach (var Emitter in _editorState.Effect.Emitters)
                //    if (Emitter.Distributor == Tag)
                //        Emitter.Distributor = null;
            }

            BuildTreeView();
            _editorState._hasUnsavedChanges = true;
        }

       


        
    }
}
